//
//  MBOnViewController.m
//  MiBaoTu
//
//  Created by 彭康 on 16/10/19.
//  Copyright © 2016年 com.caesartech15. All rights reserved.
//

#import "MBOnlinePlayController.h"
#import "MBOnlineController.h"
#import "MBSpaceMyParentChildShowTabbarView.h"
#import "MBTheNewCell.h"
#import "MBDetailViewController.h"
#import "MBMusicCell.h"
#import "MBSongDetailController.h"
#import "MBMusicICell.h"
#import "MBSongDetailForIController.h"

#import "MBSongDetailForIpadController.h"
static NSString *ID = @"MBMusicCell";
@interface MBOnlinePlayController ()<MBSpaceMyParentChildShowTabbarViewDelegate,UICollectionViewDelegate,UICollectionViewDataSource>{
    int                                     page;
    NSMutableArray                          *_mutArr;
    
    NSMutableArray                          *_onLineArr;
    NSInteger                               onlineSelectIndex;
}
@property (nonatomic, strong) UICollectionViewFlowLayout *flowLayout;

@property (nonatomic, strong) NSMutableArray*radioDateArr;

@end
@implementation MBOnlinePlayController

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    page = 1;
    _mutArr = [[NSMutableArray alloc]init];
    _radioDateArr=[[NSMutableArray alloc]init];
    _onLineArr = [[NSMutableArray alloc]init];
    onlineSelectIndex = 0;
    float heith = 0;
    heith = 80*PERCEN_HEIGHT;
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    self.flowLayout = flowLayout;

    _collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0,0, SCREEN_WIDTH, self.view.height-(heith > 0 ? 80*PERCEN_HEIGHT+NAV_HEIGHT+20 : 0))collectionViewLayout:flowLayout];
    _collectionView.delegate = self;
    _collectionView.dataSource = self;
    _collectionView.backgroundColor = [UIColor clearColor];
    [self.view addSubview:_collectionView];
    // 加载xib文件
    UINib *nib = [UINib nibWithNibName:@"MBMusicCell" bundle:nil];

    [self.collectionView registerNib:nib forCellWithReuseIdentifier:ID];
    //加载iPad cell
    [self.collectionView registerClass:[MBMusicICell class] forCellWithReuseIdentifier:@"MBMusicICell"];
    
    
    [self.collectionView addLegendFooterWithRefreshingTarget:self refreshingAction:@selector(onLoadMore)];
    [self.collectionView addLegendHeaderWithRefreshingTarget:self refreshingAction:@selector(onLoadNew)];
    if (self.type==MBOnlineShowType_Online) {
        [self loadData];
    }
}

#pragma mark--获取音频资料
-(void)getRadio:(NSNumber*)num {
    NSString*url=[NSString stringWithFormat:ONLINE_GET_RADIO_URL_PATH,num];
  
    [[HTTPManager standerDefault]AFGetRequest:url view:nil success:^(id json) {
        
        if ([json[@"ret_code"] integerValue]==0){
            NSArray*array=json[@"data"];
            if (array.count>0) {
                [_radioDateArr addObjectsFromArray:array];
            }
          
            
            UserManager *manager = [UserManager standerDefult];
            
            NSString *idStr ;
            if (manager.audioPlayerType != AudioPLayerType_YinPin) {
                //初次进入
                idStr = @"";
                manager.audioPlayerType = AudioPLayerType_YinPin;
            } else {
                //2次进入
                NSInteger selectIndex = manager.selectMusicIndex;
                NSArray *arr = manager.musicArr;
                Music *dics = [arr objectAtIndex:selectIndex];
                idStr = [NSString stringWithFormat:@"%@",dics.ID];
            }
            
            [manager setSelectMusicIndex:0];
            [manager.musicArr removeAllObjects];
            [manager.musicArr addObjectsFromArray:[manager onTurnArrayFormOnLineArray:_radioDateArr]];
             manager.selectMusicIndex = 0;
           

            
            
            
        MBSongDetailForIController*childShowVC = [[MBSongDetailForIController alloc] init];
              childShowVC.dataAllArr=_radioDateArr;
              childShowVC.selectMusicID = idStr;
            childShowVC.type=IdentityType_online;
            childShowVC.isFromOnLine=YES;
        [self.navigationController pushViewController:childShowVC animated:YES];
        }
    } failure:^(NSError *error) {
        NSLog(@"error==%@",error);
    }];
}

-(void)getRadioByOnline:(NSString*)num  withIndex:(NSInteger)indexPath{
    NSString*url=[NSString stringWithFormat:ONLINE_GET_RADIO_URL_PATH,num];
    [MBProgressHUD showHUDAddedTo:_collectionView animated:YES];
    [[HTTPManager standerDefault]AFGetRequest:url view:nil success:^(id json) {
        [MBProgressHUD hideHUDForView:_collectionView animated:YES];
        //在线电台，包含很多首歌曲，切换电台，包含的歌曲也要替换
        if ([json[@"ret_code"] integerValue]==0){
            NSArray*array=json[@"data"];
            [_onLineArr removeAllObjects];
            if (array.count>0) {
                
                [_onLineArr addObjectsFromArray:array];
                onlineSelectIndex = indexPath;
                [self onSetUpMusicPLayer];

            }
        }  else {
            [ErrorMessage showErrorMessage:@"暂无数据" inView:self.view];
        }
    } failure:^(NSError *error) {
        [MBProgressHUD hideHUDForView:_collectionView animated:YES];
    }];
}

- (void)onSetUpMusicPLayer
{
    if (_onLineArr.count == 0) return;
    if (self.type == MBOnlineShowType_Online) {
        if (_mutArr.count <= onlineSelectIndex || onlineSelectIndex < 0) return;
    }
    
    UserManager *manager = [UserManager standerDefult];
    
    if (manager.musicPlayType != MusicPLayType_Online) {
        //初次进入
        [manager playMusicWithMusicArray:_onLineArr withCurrentIndex:0 withMusicPlayType:MusicPLayType_Online];
        [manager setZhubo_SelectIndex:[NSString stringWithFormat:@"%d",(int)onlineSelectIndex]];
    }
    else if (![manager.zhubo_SelectIndex isEqualToString:[NSString stringWithFormat:@"%d",(int)onlineSelectIndex]]) {
        //不是当前页面播放
        [manager playMusicWithMusicArray:_onLineArr withCurrentIndex:0 withMusicPlayType:MusicPLayType_Online];
        [manager setZhubo_SelectIndex:[NSString stringWithFormat:@"%d",(int)onlineSelectIndex]];
    }
    else {
        //2次点击进入播放页面
        if (manager.musicArr.count > 0) {
            //歌曲列表没歌曲 无需进入
            if (manager.audioPlayerType != AudioPLayerType_YinPin) {
                [manager setIsPlaying:NO];
                [manager setAudioPlayerType:AudioPLayerType_YinPin];
            } else {
                [manager setIsPlaying:YES];
            }
            
            if (ISIPAD) {
                MBSongDetailForIpadController*song=[[MBSongDetailForIpadController alloc]init];
                song.isFromOnLine = YES;
                [self.navigationController pushViewController:song animated:YES];
                return;
            }
            MBSongDetailController *song = [[MBSongDetailController alloc]init];
            song.isFromOnLine = YES;
            [self.navigationController pushViewController:song animated:YES];
        }
        
    }
}

#pragma mark -加载数据
- (void)onLoadNew
{
    if (self.type == MBOnlineShowType_Online) {
        page = 1;
        [self loadData];
    } else {
        [self.collectionView.header endRefreshing];
        [self.collectionView.footer endRefreshing];
        [_collectionView reloadData];
    }
    
}

- (void)onLoadMore
{
    if (self.type == MBOnlineShowType_Online) {
        ++page;
        [self loadData];
    } else {
        [self.collectionView.header endRefreshing];
        [self.collectionView.footer endRefreshing];
        [_collectionView reloadData];
    }
}

- (void)loadData
{
    NSNumber *p =[NSNumber numberWithInt:page];
    NSString *url = [NSString stringWithFormat:ONLINE_RADIO_LIST_URL_PATH,p];
    [[HTTPManager standerDefault]AFGetRequest:url view:nil success:^(NSDictionary *json) {
        [self.collectionView.header endRefreshing];
        [self.collectionView.footer endRefreshing];
        
   
        if ([json isKindOfClass:[NSDictionary class]]) {
            if ([json[@"ret_code"] integerValue]==0) {
                NSArray *arr = json[@"data"];
                if (arr.count > 0) {
                    if (page == 1) {
                        [_mutArr removeAllObjects];
                    }
                    [_mutArr addObjectsFromArray:arr];
                    [_collectionView reloadData];
                }
            } else {
                [ErrorMessage showErrorMessage:json[@"message"] inView:self.view];
            }
        }
    } failure:^(NSError *error) {
        [self.collectionView.header endRefreshing];
        [self.collectionView.footer endRefreshing];
    }];

}
#pragma mark---加载DB数据
-(NSArray*)getDate{
    NSArray*array=[[FMManageObject standerDefault]onSelectRadioAudioPlayForRecent];
    
    return array;
}
#pragma mark - 选择器
- (void)onSelectItemForView:(MBSpaceMyParentChildShowTabbarView *)view withIndex:(NSInteger)selectIndex
{
    if (selectIndex < 2) {
        self.type = (int)selectIndex;
        [_collectionView reloadData];
    }
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    if (self.type==MBOnlineShowType_Online) {
          return _mutArr.count;
    }
    else{
        return [self getDate].count;
    }
  
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    if (ISIPAD) {
  
        
        MBMusicICell*cell=[collectionView dequeueReusableCellWithReuseIdentifier:@"MBMusicICell" forIndexPath:indexPath];
        if (self.type==MBOnlineShowType_Online) {
            
            cell.dateDic=_mutArr[indexPath.row];
        }else if(self.type==MBOnlineShowType_RecentlyPlay){
            
            cell.dateDic=[self getDate][indexPath.row];
            
        }

        return cell;

    }

    MBMusicCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:ID forIndexPath:indexPath];
    if (self.type==MBOnlineShowType_Online) {
        cell.dataDic = [_mutArr objectAtIndex:indexPath.row];
    }else if(self.type==MBOnlineShowType_RecentlyPlay){
        cell.dataDic=[self getDate][indexPath.row];
    }

    return cell;
}

-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
//    if (ISIPAD) {
//  
//        if (self.type==MBOnlineShowType_Online) {
//            NSMutableDictionary*dict=_mutArr[indexPath.row];
//           
//            NSString*ID=[NSString stringWithFormat:@"%@",dict[@"ID"]];
//            
//            FMManageObject*manager=[FMManageObject standerDefault];
//            [manager insertTableRadioAudioPlayForRecentWithId:ID withRaduiName:dict[@"RadioName"] withMainPicture:dict[@"MainPicture"]];
//            [self getRadio:@1];
//            
//            
//            
//            return;
//
//        }else{
//              NSMutableDictionary*dict=[self getDate][indexPath.row];
//              [self getRadio:@1];
//              return;
//        }
//        
//    }
    
    //iphone
    if (self.type == MBOnlineShowType_Online) {
        NSDictionary *dic = [_mutArr objectAtIndex:indexPath.row];
        
        
        NSString *idStr = [NSString stringWithFormat:@"%@",[dic objectForKey:@"ID"] ];
        if (idStr.length > 0) {
            //存入最近电台
            FMManageObject*manager=[FMManageObject standerDefault];
            [manager insertTableRadioAudioPlayForRecentWithId:idStr withRaduiName:dic[@"RadioName"] withMainPicture:dic[@"MainPicture"]];
            
            if (_onLineArr.count > 0 && onlineSelectIndex == indexPath.row) {
                //点击的同一个cell2次，没必要再次请求接口
                [self onSetUpMusicPLayer];
            } else {
                //初次或者切换电台
                [self getRadioByOnline:idStr withIndex:indexPath.row];
            }
        }
    }
    else if (self.type == MBOnlineShowType_RecentlyPlay) {
        NSArray *arr = [self getDate];
        NSDictionary *dic = [arr objectAtIndex:indexPath.row];
        NSString *idStr = [NSString stringWithFormat:@"%@",[dic objectForKey:@"ID"] ];
        if (idStr.length > 0) {
            if (_onLineArr.count > 0 && onlineSelectIndex == indexPath.row) {
                //点击的同一个cell2次，没必要再次请求接口
                [self onSetUpMusicPLayer];
            } else {
                //初次或者切换电台
                [self getRadioByOnline:idStr withIndex:indexPath.row];
            }
        }

    }

}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (ISIPAD) {
        CGFloat width = (SCREEN_WIDTH-4*80*PERCEN)/3;
        return CGSizeMake(width, width+70*PERCEN);
    }
    float itemWidth = ( SCREEN_WIDTH - 5*PERCEN)/2.;
    return CGSizeMake(itemWidth, 198);
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section
{
    if (ISIPAD) {
        return 60*PERCEN;
    }
    return 1;
}
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section
{
    if (ISIPAD) {
        return 80*PERCEN;
    }
    return 1;
}
-(UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section{
    if (ISIPAD) {
        return UIEdgeInsetsMake(30*PERCEN, 80*PERCEN,80*PERCEN, 60*PERCEN);
    }
    return UIEdgeInsetsMake(0,0,0,0);
}


@end
